#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <iostream>
using namespace std;
#define BUF_SIZE 100
#define EPOLL_SIZE 50
int main(int argc, char **argv)
{
    int serv_sock, clnt_sock;
    sockaddr_in serv_adr, clnt_adr;
    socklen_t adr_sz;
    int str_len, i;
    char buf[BUF_SIZE];
    struct epoll_event *ep_events;
    struct epoll_event event;
    int epfd, event_cnt;
    if (argc != 2)
    {
        printf("Usage : %s <port>\n", argv[0]);
        exit(1);
    }
    serv_sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_port = htons(atoi(argv[1]));
    bind(serv_sock, (sockaddr *)&serv_adr, sizeof(serv_adr));
    listen(serv_sock, 5);
    epfd = epoll_create(EPOLL_SIZE);
    event.data.fd = serv_sock;
    event.events = EPOLLIN;
    ep_events = new struct epoll_event[EPOLL_SIZE];
    epoll_ctl(epfd, EPOLL_CTL_ADD, serv_sock, &event);
    while (1)
    {
        event_cnt = epoll_wait(epfd, ep_events, EPOLL_SIZE, -1);
        if (event_cnt == -1)
        {
            std::cerr << "epoll_wait() error" << std::endl;
            break;
        }
        for (int i = 0; i < event_cnt; i++)
        {
            if (ep_events[i].data.fd == serv_sock)
            {
                adr_sz = sizeof(clnt_adr);
                clnt_sock = accept(serv_sock, (sockaddr *)&clnt_adr, &adr_sz);
                event.data.fd = clnt_sock;
                event.events = EPOLLIN;
                epoll_ctl(epfd, EPOLL_CTL_ADD, clnt_sock, &event);
                cout << "收到了新的客户端，文件描述符是：" << clnt_sock << endl;
            }
            else
            {
                str_len = read(ep_events[i].data.fd, buf, BUF_SIZE);
                if (str_len == 0)
                {
                    epoll_ctl(epfd, EPOLL_CTL_DEL, ep_events[i].data.fd, nullptr);
                    close(ep_events[i].data.fd);
                    printf("已经关闭了客户端：%d \n", ep_events[i].data.fd);
                }
                else
                {
                    write(ep_events[i].data.fd, buf, BUF_SIZE);
                }
            }
        }
    }
    close(serv_sock);
    close(epfd);
    return 0;
}
